package models

import (
	"NewEdu/utils"
	"context"
	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/dgrijalva/jwt-go"
)

const (
	CurrentUser = "currentUser"
)

func GetJwtString(expire int, sn, name string, role int8) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	now := time.Now()
	claims["exp"] = now.Add(time.Second * time.Duration(expire)).Unix()
	claims["iat"] = now.Unix()
	claims["name"] = name
	claims["sn"] = sn
	claims["r"] = role // 0是学员，1 是管理员.2是校区工作员
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(utils.GetJWTSecret()))
	return tokenString, err
}

type UserPswd struct {
	Oldpswd string
	Newpswd string
}

func UpdatePswd(sn, oldpswd, newpswd string) (err error) {
	// 获取用户信息
	v, err := GetTUserById(sn)
	if err != nil {
		return fmt.Errorf("用户不存在")
	}

	// 验证旧密码
	if !utils.CheckPasswordHash(oldpswd, v.Pswd) {
		return fmt.Errorf("旧密码不正确")
	}

	// 加密新密码
	hashPassword, err := utils.HashPassword(newpswd)
	if err != nil {
		return fmt.Errorf("密码加密失败: %v", err)
	}

	// 更新数据库
	o := orm.NewOrm()
	qs := o.QueryTable(new(TUser)).Filter("sn", sn)
	_, err = qs.Update(orm.Params{"pswd": hashPassword})
	if err != nil {
		return fmt.Errorf("密码更新失败: %v", err)
	}

	// 更新Redis中的用户信息
	v.Pswd = hashPassword
	uploadUserInfo2Redis(context.Background(), v)

	return nil
}
